package com.lastproject.ejb.util;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.lastproject.dto.BorrowedDTO;
import com.lastproject.ejb.entities.Book;
import com.lastproject.ejb.entities.Borrowed;
import com.lastproject.ejb.entities.User;

/**
 * Session Bean implementation class BorrowedConversion
 */
@Stateless
@LocalBean
public class BorrowedConversion {

	/**
	 * Default constructor.
	 */
	@PersistenceContext
	EntityManager em;

	public BorrowedConversion() {
		// TODO Auto-generated constructor stub
	}

	public BorrowedDTO fromEntity(Borrowed b) {

		BorrowedDTO borrowedDTO = new BorrowedDTO();
		borrowedDTO.setId(b.getId());
		borrowedDTO.setBorrowDate(b.getBorrowDate());
		borrowedDTO.setMustReturnDate(b.getMustReturnDate());
		borrowedDTO.setReturnDate(b.getReturnDate());
		borrowedDTO.setIdBook(b.getBook().getId());
		borrowedDTO.setIdUser(b.getUser().getId());
		return borrowedDTO;

	}

	public Borrowed fromDTO(BorrowedDTO borrowedDTO) {

		Borrowed borrowed = em.find(Borrowed.class, borrowedDTO.getId());

		if (borrowed == null) {
			borrowed = new Borrowed();
		}

		borrowed.setBook(em.find(Book.class, borrowedDTO.getIdBook()));
		borrowed.setUser(em.find(User.class, borrowedDTO.getIdUser()));
		borrowed.setBorrowDate(borrowedDTO.getBorrowDate());
		borrowed.setMustReturnDate(borrowedDTO.getMustReturnDate());
		borrowed.setReturnDate(borrowedDTO.getReturnDate());

		return borrowed;

	}
}
